<!-- src/packageG/components/EnhancedProductList.vue -->
<template>
  <view class="product-list">
    <!-- 商品列表 -->
    <view class="goods-list" :class="{ 'two-column': twoColumn }">
      <view
        class="goods-item"
        :class="{ 'two-column-item': twoColumn }"
        v-for="(item, index) in productList"
        :key="item.id || index"
        @click="handleProductClick(item, index)"
      >
        <slot name="product-item" :item="item" :index="index">
          <!-- 默认商品展示 -->
          <view class="goods-item-default">
            <view class="goods-img">
              <image
                :style="getImageStyle()"
                :src="item.image || item.img"
                mode="aspectFill"
              />
            </view>
            <view class="goods-bottom">
              <view class="goods-name">{{ item.name || item.title }}</view>
              <view class="goods-title" v-if="showTags">
                <view class="title" v-if="item.tag">
                  <u-tag size="mini" :text="item.tag" type="warning" />
                </view>
                <view class="sub-title" v-if="item.recommendValue">
                  <image
                    v-if="hotIcon"
                    style="width: 25rpx; height: 25rpx"
                    :src="hotIcon"
                    mode="scaleToFill"
                  />
                  <text>{{ item.recommendValue }}</text>
                </view>
              </view>
              <view class="price-section">
                <span class="goods-price"
                  >￥{{ item.currentUserMoney || item.price }}</span
                >
                <span
                  class="original"
                  v-if="
                    item.currentUserMoney != item.money && showOriginalPrice
                  "
                >
                  ￥{{ item.money }}
                </span>
              </view>
            </view>
          </view>
        </slot>
      </view>
    </view>

    <!-- 空状态 -->
    <view v-if="productList.length === 0 && !loading" class="empty-state">
      <slot name="empty">
        <view class="empty-default">
          <u-image
            v-if="emptyImage"
            :src="emptyImage"
            width="50%"
            height="300rpx"
            mode="heightFix"
          />
          <view class="fw700" style="margin: 20rpx 0">{{ emptyText }}</view>
          <view style="color: #999999">{{ emptySubText }}</view>
        </view>
      </slot>
    </view>

    <!-- 加载提示 -->
    <view class="loading-tip" v-if="loading && productList.length > 0">
      <u-loading mode="circle" size="30"></u-loading>
      <text style="margin-left: 20rpx">加载中...</text>
    </view>

    <view class="loading-tip" v-if="noMoreData && productList.length > 0">
      <text>没有更多数据了</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { onLoad, onPullDownRefresh } from '@dcloudio/uni-app'
import {
  ref,
  onMounted,
  watch,
  defineProps,
  defineEmits,
  withDefaults
} from 'vue'
import { productApi } from '@/api'
import list from '../static/list.png'
interface Product {
  id?: string | number
  name?: string
  title?: string
  image?: string
  img?: string
  price?: number | string
  currentUserMoney?: number | string
  money?: number | string
  recommendValue?: string | number
  tag?: string
  productId?: string | number
  [key: string]: any
}

interface Props {
  // 数据获取相关属性
  autoLoad?: boolean // 是否自动加载数据
  shopId?: number | string // 店铺ID
  categoryId?: number | string // 分类ID
  keywords?: string // 搜索关键词
  pageSize?: number // 每页数量

  // 显示相关属性
  twoColumn?: boolean // 是否双列显示
  showTags?: boolean // 是否显示标签
  showOriginalPrice?: boolean // 是否显示原价
  emptyText?: string
  emptySubText?: string
  emptyImage?: string
  hotIcon?: string
  imageHeight?: string
  imageWidth?: string
  shopMode?: string
}

const props = withDefaults(defineProps<Props>(), {
  autoLoad: true,
  pageSize: 10,
  twoColumn: true,
  showTags: true,
  showOriginalPrice: true,
  emptyText: '暂无商品',
  emptySubText: '列表暂无任何商品奥~',
  emptyImage: list,
  imageHeight: '340rpx',
  imageWidth: '100%'
})

// 响应式数据
const productList = ref<Product[]>([])
const loading = ref(false)
const noMoreData = ref(false)
const pagination = ref({
  pageIndex: 1,
  total: 0
})

// 定义事件
const emit = defineEmits<{
  (e: 'productClick', product: Product, index: number): void
  (e: 'loadSuccess', data: any): void
  (e: 'loadError', error: any): void
}>()

// 获取商品列表数据
const loadProductList = async (isLoadMore = false) => {
  // 如果正在加载或没有更多数据，直接返回
  if (loading.value || noMoreData.value) return

  // 如果是加载更多，增加页码
  if (isLoadMore) {
    pagination.value.pageIndex++
  } else {
    // 刷新时重置分页信息
    pagination.value.pageIndex = 1
    noMoreData.value = false
    productList.value = []
  }

  loading.value = true

  try {
    const params: any = {
      pageIndex: pagination.value.pageIndex,
      pageSize: props.pageSize
    }

    // 添加可选参数
    if (props.shopId) params.shopId = props.shopId
    if (props.categoryId) params.categoryId = props.categoryId
    if (props.keywords) params.keywords = props.keywords
    if (props.shopMode) params.shopMode = props.shopMode

    const { data } = await productApi.getShopProductList(params)

    pagination.value.total = data.total

    if (isLoadMore) {
      // 加载更多时追加数据
      productList.value = [...productList.value, ...data.records]
    } else {
      // 刷新时替换数据
      productList.value = data.records
    }

    // 判断是否还有更多数据
    noMoreData.value = productList.value.length >= pagination.value.total

    emit('loadSuccess', data)
  } catch (error: any) {
    console.error('获取商品列表失败:', error.msg)
    // 如果加载失败，页码回退
    if (isLoadMore) {
      pagination.value.pageIndex--
    }
    emit('loadError', error)
  } finally {
    loading.value = false
  }
}

// 加载更多数据
const loadMore = () => {
  loadProductList(true)
}

// 刷新数据
const refresh = () => {
  loadProductList(false)
}

// 处理商品点击
const handleProductClick = (product: Product, index: number) => {
  emit('productClick', product, index)
}

// 获取图片样式
const getImageStyle = () => {
  return {
    width: props.imageWidth,
    height: props.imageHeight,
    'border-top-left-radius': '10rpx',
    'border-top-right-radius': '10rpx'
  }
}

onLoad(() => {
  console.log('接收的参数', props)
})
// 自动加载数据
onMounted(() => {
  if (props.autoLoad) {
    loadProductList()
  }
})

// 监听参数变化，重新加载数据
watch(
  [() => props.shopId, () => props.categoryId, () => props.keywords],
  () => {
    refresh()
  }
)

// 暴露方法给父组件
defineExpose({
  loadProductList,
  loadMore,
  refresh,
  productList,
  loading,
  noMoreData
})
</script>

<style lang="scss" scoped>
.product-list {
  .goods-list {
    &.two-column {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      justify-content: space-between;
    }
  }

  .goods-item {
    &.two-column-item {
      width: 340rpx;
      border-radius: 20rpx;
      background: #fff;
      margin-bottom: 20rpx;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
    }

    .goods-img {
      width: 100%;
    }

    .goods-bottom {
      padding: 20rpx;
    }

    .goods-name {
      height: 30rpx;
      font-size: 26rpx;
      overflow: hidden;
    }

    .goods-title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin: 10rpx 0;

      .sub-title {
        display: flex;
        align-items: center;
        font-size: 22rpx;
        color: #999999;

        image {
          width: 30rpx;
          height: 30rpx;
          vertical-align: middle;
          margin-right: 10rpx;
        }
      }
    }

    .price-section {
      .goods-price {
        font-size: 30rpx;
        font-weight: 700;
        color: #ef615b;
      }

      .original {
        margin: 0 15rpx;
        font-size: 24rpx;
        color: #999999;
        text-decoration: line-through;
      }
    }
  }

  .empty-default {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 100rpx 0;
    text-align: center;
  }

  .loading-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20rpx;
    color: #999;
  }
}

.fw700 {
  font-weight: 700;
}
</style>
